package manager.modulo.estoque.fonte;

import java.awt.event.KeyEvent;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.table.TableRowSorter;
import manager.auxiliares.AutoComplete;
import manager.auxiliares.Configurations;
import manager.auxiliares.FixedLengthDocument;
import manager.auxiliares.Format;
import manager.auxiliares.Icons;
import manager.auxiliares.MensagemExcessao;
import manager.auxiliares.WindowsFunctions;
import manager.helpers.table.TableModel;
import manager.helpers.table.TableRender;
import manager.helpers.table.TableRowComparator;
import manager.helpers.validation.FormatedFieldValidator;
import manager.helpers.validation.TextFieldValidator;
import manager.helpers.validation.ValidationFunctions;
import manager.principal.fonte.JanelaLogin;
import manager.interfaces.InterfaceTable;
import manager.modulo.clientefornecedor.dao.CentroCustoDao;
import manager.modulo.clientefornecedor.dao.ClienteFornecedorDao;
import manager.modulo.estoque.dao.InsumoDao;
import manager.modulo.estoque.dao.InsumoSaidaDao;
import manager.modulo.estoque.dao.SaidaEstoqueDAO;
import manager.modulo.estoque.enumerator.EnumTipoInsumo;
import manager.modulo.estoque.enumerator.EnumTipoSaidaEstoque;
import manager.modulo.estoque.enumerator.EnumUnidadeInsumo;
import manager.modulo.sistema.dao.UsuarioDao;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author Thiago
 */
public class JanelaSaidaEstoque extends javax.swing.JFrame {

    //Entrada de Estoque
    int idSaidaEstoque = 0;
    AutoComplete autoCompletarCentroCusto;
    int index = 0;
    boolean selecionado = false;
    TableModel tableModel;
    TableRender tableRender;
    TableRowSorter tableRowSorter;
    LinkedList<InsumoDao> listaInsumos;
    AutoComplete autoCompletarInsumoIdentificador;
    AutoComplete autoCompletarInsumoNome;

    public JanelaSaidaEstoque() {
    }

    /**
     * Creates new form UserWindow
     */
    public JanelaSaidaEstoque(int id) {
        try {
            // Define layout de acordo com o SO que estiver rodando
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            this.setIconImage(JanelaLogin.icon);
            initComponents();
            idSaidaEstoque = id;
            configurarJanela();
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }

    private LinkedList<String> getNomeColunasTabelaInsumos() {
        LinkedList<String> listaNomesColunas = new LinkedList<String>();
        listaNomesColunas.add("");
        listaNomesColunas.add("Item");
        listaNomesColunas.add("Ident.");
        listaNomesColunas.add("Nome");
        listaNomesColunas.add("Unid.");
        listaNomesColunas.add("Quant.");
        return listaNomesColunas;
    }

    private void carregarInformacoesInsumo() {
        jButton2.setToolTipText("Editar");
        jButton2.setIcon(new Icons().getEdit());
        if (idSaidaEstoque == 0) {
            jButton2.setEnabled(true);
            jButton4.setEnabled(true);
        }
        jButton3.setEnabled(true);
        InsumoDao insumoDao = listaInsumos.get(index);
        jTextField8.setText(insumoDao.getIdentificador());
        selecionarInsumo(insumoDao, true);
        jTextField13.setText(Double.toString(((double) insumoDao.getQuantidade()) / 100));
        jTextField8.requestFocus();
    }

    private void configureTable() {
        tableRender = new TableRender();
        tableModel = new TableModel(getNomeColunasTabelaInsumos(), tableRender, new InterfaceTable() {
            public void tableAction(int id, int columnIndex, int rowIndex) {
                if (columnIndex < 0) {
                    if (!selecionado) {
                        index = rowIndex;
                        selecionado = true;
                        carregarInformacoesInsumo();
                    }
                }
            }

            public boolean isEditableColumn(int columnIndex) {
                if (columnIndex == 0) {
                    return true;
                }
                return false;
            }
        });
        jTable1.setModel(tableModel);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(30);
        jTable1.getColumnModel().getColumn(0).setMinWidth(30);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setMaxWidth(40);
        jTable1.getColumnModel().getColumn(1).setMinWidth(40);
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(2).setMaxWidth(50);
        jTable1.getColumnModel().getColumn(2).setMinWidth(50);
        jTable1.getColumnModel().getColumn(2).setResizable(false);
        jTable1.getColumnModel().getColumn(4).setMaxWidth(40);
        jTable1.getColumnModel().getColumn(4).setMinWidth(40);
        jTable1.getColumnModel().getColumn(4).setResizable(false);
        jTable1.getColumnModel().getColumn(5).setMaxWidth(70);
        jTable1.getColumnModel().getColumn(5).setMinWidth(70);
        jTable1.getColumnModel().getColumn(5).setResizable(false);
        TableRowComparator tableRowComparator = new TableRowComparator();
        tableRowSorter = tableRowComparator;
        jTable1.setRowSelectionAllowed(false);

        buscarTabela();
    }

    private void configurarCamposEntradaEstoque() {
        ((TextFieldValidator) jTextField4).validarCampo();
        ((TextFieldValidator) jTextField3).validarCampo();

        configurarCamposInsumos();
    }

    private void configurarCamposInsumos() {
        ((TextFieldValidator) jTextField13).validarCampo();
        if (jRadioButton2.isSelected()) {
            ((TextFieldValidator) jTextField8).validarCampo();
            jLabel8.setForeground(Configurations.getFieldValidationOk());
        } else {
            ((TextFieldValidator) jTextField5).validarCampo();
            jLabel13.setForeground(Configurations.getFieldValidationOk());
        }
    }

    private void limparCamposInsumos() {
        selecionado = false;

        jTextField8.setText("");
        jTextField5.setText("");
        jTextField9.setText("");
        jTextField13.setText("");
        jTextField10.setText("");
        autoCompletarInsumoIdentificador.setSearchWord("");
        autoCompletarInsumoNome.setSearchWord("");

        jScrollPane3.setVisible(false);

        jButton2.setToolTipText("Adicionar");
        jButton2.setIcon(new Icons().getAdd());
        if (idSaidaEstoque == 0) {
            jButton2.setEnabled(true);
            configurarCamposInsumos();
        }
        jButton3.setEnabled(false);
        jButton4.setEnabled(false);
    }

    private void buscarTabela() {
        LinkedList searchResult = new LinkedList();

        LinkedList<Integer> columnId = new LinkedList<Integer>();
        LinkedList<String> colunaNumeroItem = new LinkedList<String>();
        LinkedList<String> colunaIdentificador = new LinkedList<String>();
        LinkedList<String> colunaNome = new LinkedList<String>();
        LinkedList<String> colunaUnidade = new LinkedList<String>();
        LinkedList<String> colunaQuantidade = new LinkedList<String>();

        for (int i = 0; i < listaInsumos.size(); i++) {
            InsumoDao insumoDao = listaInsumos.get(i);
            columnId.add(i);
            colunaNumeroItem.add(Integer.toString(i + 1));
            colunaIdentificador.add(insumoDao.getIdentificador());
            colunaNome.add(insumoDao.getNome());
            colunaUnidade.add(EnumUnidadeInsumo.ConvertEnumString(insumoDao.getUnidadeInsumo()));
            colunaQuantidade.add(Double.toString(((double) insumoDao.getQuantidade()) / 100));
        }


        if (listaInsumos.size() > 0) {
            searchResult.add(columnId);
            searchResult.add(Format.getBooleanLinkedList(columnId.size()));
            searchResult.add(colunaNumeroItem);
            searchResult.add(colunaIdentificador);
            searchResult.add(colunaNome);
            searchResult.add(colunaUnidade);
            searchResult.add(colunaQuantidade);
        }

        tableModel.update(searchResult);
        jTable1.setDefaultRenderer(Object.class, tableRender);
        tableRowSorter.setModel(tableModel);

        jTable1.setRowSorter(tableRowSorter);
    }

    private LinkedList<String> validarCamposEntradaEstoque() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (!((TextFieldValidator) jTextField4).validarCampo()) {// Documento
            fieldList.add(((TextFieldValidator) jTextField4).getjLabel().getText());
        }
        if (jComboBox1.getItemCount() == 0) {// Cliente Fornecedor
            fieldList.add(jLabel2.getText());
        } else if (!((TextFieldValidator) jTextField3).validarCampo() || CentroCustoDao.getIdCentroCustoPorNome(jTextField3.getSelectedText()) == 0) {// Centro de Custo
            fieldList.add(((TextFieldValidator) jTextField3).getjLabel().getText());
        }
        if (listaInsumos.size() == 0) {
            fieldList.add("Lista de materiais vazia.");
        }
        return fieldList;
    }

    private LinkedList<String> validarCamposInsumos() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (jRadioButton2.isSelected()) {
            if (!((TextFieldValidator) jTextField8).validarCampo()) {// Identificador
                fieldList.add(((TextFieldValidator) jTextField8).getjLabel().getText());
            }
        } else {
            if (!((TextFieldValidator) jTextField5).validarCampo()) {// Nome
                fieldList.add(((TextFieldValidator) jTextField5).getjLabel().getText());
            }
        }
        if (!((TextFieldValidator) jTextField13).validarCampo()) {// Quantidade
            fieldList.add(((TextFieldValidator) jTextField13).getjLabel().getText());
        }
        return fieldList;
    }

    private void adicionarSaídaEstoque() {
        try {
            try {
                if (listaInsumos.size() > 0) {
                    JanelaLogin.connection.setAutoCommit(false);


                    UsuarioDao usuarioDao = JanelaLogin.getUsuario();

                    SaidaEstoqueDAO saidaEstoqueDAO = new SaidaEstoqueDAO();
                    saidaEstoqueDAO.setIdUsuario(usuarioDao.getId());
                    saidaEstoqueDAO.setDtSaida(Format.getCurrentDatabseTimeStamp());
                    saidaEstoqueDAO.setSolicitante(jTextField4.getText());
                    saidaEstoqueDAO.setTipoSaida(EnumTipoSaidaEstoque.ConvertStringEnum(jComboBox3.getSelectedItem().toString()));
                    saidaEstoqueDAO.setIdCentroCusto(CentroCustoDao.getIdCentroCustoPorNome(jTextField3.getText()));
                    saidaEstoqueDAO.setObservacao(jTextArea2.getText());

                    saidaEstoqueDAO.inserir();

                    for (int i = 0; i < listaInsumos.size(); i++) {
                        InsumoDao insumoDao = listaInsumos.get(i);
                        InsumoSaidaDao insumoSaidaDao = new InsumoSaidaDao();
                        insumoSaidaDao.setIdInsumo(insumoDao.getId());
                        insumoSaidaDao.setIdSaida(saidaEstoqueDAO.getId());
                        insumoSaidaDao.setQuantidade(insumoDao.getQuantidade());

                        insumoSaidaDao.inserir();

                        InsumoDao insumoEstoque = new InsumoDao();
                        insumoEstoque.buscar(insumoDao.getId());

                        insumoEstoque.setQuantidade(insumoEstoque.getQuantidade() - insumoDao.getQuantidade());

                        insumoEstoque.atualizar();
                    }

                    JanelaLogin.connection.commit();
                    JOptionPane.showMessageDialog(null, "Saída do estoque cadastrada com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);

                    Object[] options = {"Sim", "Não"};
                    int j = JOptionPane.showOptionDialog(null, "Deseja imprimir esta saída de estoque?", "Saída de Estoque", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (j == JOptionPane.YES_OPTION) {
                        this.imprimir(saidaEstoqueDAO.getId());
                    }
                    this.dispose();
                } else {
                    JOptionPane.showMessageDialog(null, "Adicione pelo menos um insumo a saída do estoque.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                JanelaLogin.connection.rollback();
                MensagemExcessao.mostrarMensagem(e, this.getTitle());
            } finally {
                JanelaLogin.connection.setAutoCommit(true);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    private void adicionarInsumo() {
        try {
            int idInsumoBuscado = InsumoDao.getIdInsumoPorIdentificador(jTextField8.getText());
            if (idInsumoBuscado != 0) {
                InsumoDao insumoDao = new InsumoDao();
                insumoDao.buscar(idInsumoBuscado);
                if (insumoDao.getTipoInsumo() == EnumTipoInsumo.TipoInsumo.MT) {
                    insumoDao.setQuantidade((int) (Format.formatarStringDouble(jTextField13.getText()) * 100));
                    if (!selecionado) {
                        listaInsumos.add(insumoDao);
                    } else {
                        listaInsumos.set(index, insumoDao);
                    }
                    limparCamposInsumos();

                    buscarTabela();
                } else {
                    JOptionPane.showMessageDialog(null, "Este tipo de insumo não pode ser retirado ou inserido do estoque.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Insumo não encontrado.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }

        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    private void carregarInformacoes() {
        jButton1.setText("Editar");
        jButton1.setIcon(new Icons().getEdit());
        jButton1.setEnabled(false);


        SaidaEstoqueDAO saidaEstoqueDAO = new SaidaEstoqueDAO();
        saidaEstoqueDAO.buscar(idSaidaEstoque);

        UsuarioDao usuarioDao = new UsuarioDao();
        usuarioDao.buscar(saidaEstoqueDAO.getIdUsuario());
        jTextField1.setText(usuarioDao.getNome());

        jFormattedTextField1.setText(Format.formatarTimeStampApresentacao(saidaEstoqueDAO.getDtSaida()));
        jTextField4.setText(saidaEstoqueDAO.getSolicitante());
        jComboBox3.setSelectedItem(EnumTipoSaidaEstoque.ConvertEnumString(saidaEstoqueDAO.getTipoSaida()));

        CentroCustoDao centroCustoDao = new CentroCustoDao();
        centroCustoDao.buscar(saidaEstoqueDAO.getIdCentroCusto());
        jTextField3.setText(centroCustoDao.getNome());

        ClienteFornecedorDao clienteFornecedorDao = new ClienteFornecedorDao();
        clienteFornecedorDao.buscar(centroCustoDao.getIdClienteFornecedor());
        jComboBox1.setSelectedItem(clienteFornecedorDao.getIdentificador());

        jTextArea2.setText(saidaEstoqueDAO.getObservacao());

        LinkedList<InsumoSaidaDao> listaInsumosSaida = InsumoSaidaDao.listarInsumosPorSaida(saidaEstoqueDAO.getId());

        for (int i = 0; i < listaInsumosSaida.size(); i++) {
            InsumoSaidaDao insumoSaidaDao = listaInsumosSaida.get(i);
            InsumoDao insumoDao = new InsumoDao();
            insumoDao.buscar(insumoSaidaDao.getIdInsumo());
            insumoDao.setQuantidade(insumoSaidaDao.getQuantidade());
            listaInsumos.add(insumoDao);
        }

        buscarTabela();
    }

    /**
     * Inicializando as configurações da tela
     *
     * @throws SQLException
     */
    private void configurarJanela() throws SQLException {
        autoCompletarCentroCusto = new AutoComplete(jList3, jScrollPane6, jTextField3);
        listaInsumos = new LinkedList<InsumoDao>();

        autoCompletarInsumoIdentificador = new AutoComplete(jList2, jScrollPane3, jTextField8);
        autoCompletarInsumoNome = new AutoComplete(jList4, jScrollPane4, jTextField5);

        configureTable();

        LinkedList<String> listaClientesFornecedores = ClienteFornecedorDao.getListaIdentificadorClienteFornecedor();
        for (int i = 0; i < listaClientesFornecedores.size(); i++) {
            jComboBox1.addItem(listaClientesFornecedores.get(i).toString());
        }

        LinkedList<String> listaTiposSaidas = EnumTipoSaidaEstoque.ListaStringTipos();
        for (int i = 0; i < listaTiposSaidas.size(); i++) {
            jComboBox3.addItem(listaTiposSaidas.get(i).toString());
        }

        jComboBox3.setSelectedItem(EnumTipoSaidaEstoque.ConvertEnumString(EnumTipoSaidaEstoque.TipoSaidaEstoque.EXECUCAOOBRA));

        if (idSaidaEstoque != 0) {
            carregarInformacoes();
            jTextField1.setEnabled(false);
            jTextField4.setEnabled(false);
            jTextField8.setEnabled(false);
            jButton2.setEnabled(false);
            jComboBox3.setEnabled(false);
            jComboBox1.setEnabled(false);
            jTextField3.setEnabled(false);
            jTextArea2.setEnabled(false);
            jTextField13.setEnabled(false);
            jRadioButton1.setEnabled(false);
            jRadioButton2.setEnabled(false);
        } else {

            UsuarioDao usuarioDao = JanelaLogin.getUsuario();
            jTextField1.setText(usuarioDao.getNome());

            configurarCamposEntradaEstoque();
        }

    }

    private void selecionarInsumo(InsumoDao insumoBuscado, boolean opcao) {
        InsumoDao insumoDao = new InsumoDao();
        if (insumoBuscado == null) {
            int idInsumoDao = 0;
            if (opcao) {// Identificador
                idInsumoDao = InsumoDao.getIdInsumoPorIdentificador(jTextField8.getText());
            } else {
                idInsumoDao = InsumoDao.getIdInsumoPorNome(jTextField5.getText());
            }
            insumoDao.buscar(idInsumoDao);
        } else {
            insumoDao = insumoBuscado;
        }
        if (opcao) { //Identificador
            jScrollPane3.setVisible(false);
            jTextField8.requestFocus();
        } else {
            jScrollPane4.setVisible(false);
            jTextField5.requestFocus();
        }

        if (insumoDao.getId() != 0) {
            jTextField5.setText(insumoDao.getNome());
            jTextField8.setText(insumoDao.getIdentificador());
            jTextField9.setText(EnumUnidadeInsumo.ConvertEnumString(insumoDao.getUnidadeInsumo()));
            jTextField10.setText(Double.toString(((double) insumoDao.getQuantidade()) / 100));
        } else {
            if (opcao) {
                jTextField5.setText("");
            } else {
                jTextField8.setText("");
            }
            jTextField9.setText("");
            jTextField10.setText("");
        }
    }

    public void modificarOpcaoAutocompletar(boolean opcao) {
        jTextField8.setEnabled(opcao);
        jTextField5.setEnabled(!opcao);
        jScrollPane3.setVisible(false);
        jScrollPane4.setVisible(false);
        limparCamposInsumos();
    }

    public void imprimir(int id) {
        try {
            HashMap parameters = new HashMap();

            parameters.put("idSaidaEstoque", id);
            InputStream is = this.getClass().getClassLoader().getResourceAsStream("manager/modulo/estoque/relatorio/SaidaEstoque.jasper");
            Connection connection = JanelaLogin.getConnection();
            JasperPrint relat = JasperFillManager.fillReport(is, parameters, connection);
            JasperViewer.viewReport(relat, false);
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, "Saida do Estoque");
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel13 = new javax.swing.JLabel();
        jTextField8 = new TextFieldValidator(-1, -1, true, true, "text", jLabel13);
        jScrollPane3 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton4 = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jTextField5 = new TextFieldValidator(-1, -1, true, true, "text", jLabel8);
        jScrollPane4 = new javax.swing.JScrollPane();
        jList4 = new javax.swing.JList();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel11 = new javax.swing.JLabel();
        jTextField9 = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jTextField13 = new TextFieldValidator(10, 1, true, true, "double", jLabel11);
        jTextField10 = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jButton1 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jFormattedTextField1 = new FormatedFieldValidator(true, true, "date", jLabel6);
        jLabel7 = new javax.swing.JLabel();
        jTextField4 = new TextFieldValidator(40, -1, true, true, "text", jLabel7);
        jComboBox3 = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        jLabel44 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane6 = new javax.swing.JScrollPane();
        jList3 = new javax.swing.JList();
        jTextField3 = new manager.helpers.validation.TextFieldValidator(80,-1,true,true,"text",jLabel3);
        jScrollPane5 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("SAÍDA DO ESTOQUE");
        setBackground(Configurations.getBackGroundColor());
        setMinimumSize(new java.awt.Dimension(601, 450));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel3.setBackground(Configurations.getBackGroundColor());
        jPanel3.setPreferredSize(new java.awt.Dimension(700, 320));
        jPanel3.setLayout(null);

        jPanel1.setBackground(Configurations.getBackGroundColor());
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setLayout(null);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Funcionário Resp. Conferência");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(20, 20, 180, 14);

        jTextField1.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField1.setEnabled(false);
        jPanel1.add(jTextField1);
        jTextField1.setBounds(20, 40, 285, 20);

        jPanel2.setBackground(Configurations.getBackGroundColor());
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("LISTA DE INSUMOS"));
        jPanel2.setLayout(null);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton2.setToolTipText("Adicionar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);
        jButton2.setBounds(590, 30, 30, 30);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton3.setToolTipText("Cancelar");
        jButton3.setEnabled(false);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton3);
        jButton3.setBounds(630, 50, 30, 30);

        jLabel13.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel13.setText("Identificador");
        jPanel2.add(jLabel13);
        jLabel13.setBounds(35, 20, 90, 14);

        jTextField8.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField8.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField8KeyReleased(evt);
            }
        });
        jPanel2.add(jTextField8);
        jTextField8.setBounds(10, 40, 120, 20);

        jScrollPane3.setVisible(false);

        jList2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jList2MouseReleased(evt);
            }
        });
        jList2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jList2KeyReleased(evt);
            }
        });
        jScrollPane3.setViewportView(jList2);

        jPanel2.add(jScrollPane3);
        jScrollPane3.setBounds(10, 60, 120, 50);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/remove.png"))); // NOI18N
        jButton4.setToolTipText("Remover");
        jButton4.setEnabled(false);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton4);
        jButton4.setBounds(630, 10, 30, 30);

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setText("Nome do Insumo");
        jPanel2.add(jLabel8);
        jLabel8.setBounds(155, 20, 110, 14);

        jTextField5.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField5.setEnabled(false);
        jTextField5.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField5KeyReleased(evt);
            }
        });
        jPanel2.add(jTextField5);
        jTextField5.setBounds(135, 40, 250, 20);

        jScrollPane4.setVisible(false);

        jList4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jList4MouseReleased(evt);
            }
        });
        jList4.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jList4KeyReleased(evt);
            }
        });
        jScrollPane4.setViewportView(jList4);

        jPanel2.add(jScrollPane4);
        jScrollPane4.setBounds(135, 60, 250, 50);

        jScrollPane1.setViewportView(jTable1);

        jPanel2.add(jScrollPane1);
        jScrollPane1.setBounds(10, 90, 660, 140);

        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel11.setText("Quantidade");
        jPanel2.add(jLabel11);
        jLabel11.setBounds(510, 20, 70, 14);

        jTextField9.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField9.setEnabled(false);
        jPanel2.add(jTextField9);
        jTextField9.setBounds(455, 40, 50, 20);

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel12.setText("Unidade");
        jPanel2.add(jLabel12);
        jLabel12.setBounds(455, 20, 50, 14);

        jTextField13.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jPanel2.add(jTextField13);
        jTextField13.setBounds(510, 40, 70, 20);

        jTextField10.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField10.setEnabled(false);
        jPanel2.add(jTextField10);
        jTextField10.setBounds(390, 40, 60, 20);

        jLabel14.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel14.setText("Disponível");
        jPanel2.add(jLabel14);
        jLabel14.setBounds(390, 20, 60, 14);

        buttonGroup1.add(jRadioButton1);
        jPanel2.add(jRadioButton1);
        jRadioButton1.setBounds(130, 15, 21, 21);

        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setSelected(true);
        jRadioButton2.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jRadioButton2ItemStateChanged(evt);
            }
        });
        jPanel2.add(jRadioButton2);
        jRadioButton2.setBounds(10, 15, 21, 21);

        jPanel1.add(jPanel2);
        jPanel2.setBounds(10, 190, 680, 240);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(10, 440, 100, 23);

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton6.setText("Cancelar");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton6);
        jButton6.setBounds(120, 440, 100, 23);

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setText("Data da Saida");
        jPanel1.add(jLabel6);
        jLabel6.setBounds(310, 20, 110, 14);

        jFormattedTextField1.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jFormattedTextField1.setEnabled(false);
        jFormattedTextField1.setNextFocusableComponent(jTextField4);
        jPanel1.add(jFormattedTextField1);
        jFormattedTextField1.setBounds(310, 40, 110, 20);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Solicitante");
        jPanel1.add(jLabel7);
        jLabel7.setBounds(425, 20, 70, 14);

        jTextField4.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jPanel1.add(jTextField4);
        jTextField4.setBounds(425, 40, 265, 20);

        jPanel1.add(jComboBox3);
        jComboBox3.setBounds(20, 90, 140, 20);

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel10.setText("Tipo da Saída");
        jPanel1.add(jLabel10);
        jLabel10.setBounds(20, 70, 120, 14);

        jLabel44.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel44.setText("Observação");
        jPanel1.add(jLabel44);
        jLabel44.setBounds(20, 110, 80, 14);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("Cliente/Fornecedor");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(165, 70, 150, 14);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Centro de Custo");
        jPanel1.add(jLabel3);
        jLabel3.setBounds(460, 70, 150, 14);

        jScrollPane6.setVisible(false);

        jList3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jList3MouseReleased(evt);
            }
        });
        jList3.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jList3KeyReleased(evt);
            }
        });
        jScrollPane6.setViewportView(jList3);

        jPanel1.add(jScrollPane6);
        jScrollPane6.setBounds(460, 110, 230, 50);

        jTextField3.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField3.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField3KeyReleased(evt);
            }
        });
        jPanel1.add(jTextField3);
        jTextField3.setBounds(460, 90, 230, 20);

        jTextArea2.setColumns(20);
        jTextArea2.setFont(new java.awt.Font("Monospaced", 1, 10)); // NOI18N
        jTextArea2.setLineWrap(true);
        jTextArea2.setRows(2);
        jTextArea2.setWrapStyleWord(true);
        jScrollPane5.setViewportView(jTextArea2);
        jTextArea2.setDocument(new FixedLengthDocument(100));

        jPanel1.add(jScrollPane5);
        jScrollPane5.setBounds(20, 130, 670, 50);

        jPanel1.add(jComboBox1);
        jComboBox1.setBounds(165, 90, 290, 20);

        jPanel3.add(jPanel1);
        jPanel1.setBounds(0, 0, 700, 480);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 478, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        WindowsFunctions.resizePanel(jPanel3, jPanel1);
    }//GEN-LAST:event_formComponentResized

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        LinkedList<String> fieldValidadeList = validarCamposEntradaEstoque();
        if (fieldValidadeList.size() == 0) {
            adicionarSaídaEstoque();
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(fieldValidadeList), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        LinkedList<String> fieldValidadeList = validarCamposInsumos();
        if (fieldValidadeList.size() == 0) {
            adicionarInsumo();
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(fieldValidadeList), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        limparCamposInsumos();
}//GEN-LAST:event_jButton3ActionPerformed

    private void jTextField8KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField8KeyReleased
        try {
            if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                selecionarInsumo(null, true);
            } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                if (autoCompletarInsumoIdentificador.getjScrollPane().isVisible()) {
                    autoCompletarInsumoIdentificador.getjList().setSelectedIndex(0);
                    autoCompletarInsumoIdentificador.getjList().requestFocus();
                }
            } else {
                if (!autoCompletarInsumoIdentificador.getSearchWord().equals(jTextField8.getText())) {
                    autoCompletarInsumoIdentificador.setSearchWord(jTextField8.getText());
                    autoCompletarInsumoIdentificador.update(new InsumoDao().buscar("Identificador", jTextField8.getText(), true));
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }//GEN-LAST:event_jTextField8KeyReleased

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        listaInsumos.remove(index);
        limparCamposInsumos();
        buscarTabela();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jList2KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList2KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            autoCompletarInsumoIdentificador.setSearchWord(autoCompletarInsumoIdentificador.getjList().getSelectedValue().toString());
            autoCompletarInsumoIdentificador.getjScrollPane().setVisible(false);
            selecionarInsumo(null, true);
        }
    }//GEN-LAST:event_jList2KeyReleased

    private void jList2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList2MouseReleased
        autoCompletarInsumoIdentificador.setSearchWord(autoCompletarInsumoIdentificador.getjList().getSelectedValue().toString());
        autoCompletarInsumoIdentificador.getjScrollPane().setVisible(false);
        selecionarInsumo(null, true);
    }//GEN-LAST:event_jList2MouseReleased

    private void jList3MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList3MouseReleased
        autoCompletarCentroCusto.setSearchWord(autoCompletarCentroCusto.getjList().getSelectedValue().toString());
        autoCompletarCentroCusto.getjScrollPane().setVisible(false);
        jTextField3.requestFocus();
    }//GEN-LAST:event_jList3MouseReleased

    private void jList3KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList3KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            autoCompletarCentroCusto.setSearchWord(autoCompletarCentroCusto.getjList().getSelectedValue().toString());
            autoCompletarCentroCusto.getjScrollPane().setVisible(false);
            jTextField3.requestFocus();
        }
    }//GEN-LAST:event_jList3KeyReleased

    private void jTextField3KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField3KeyReleased
        try {
            if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                if (CentroCustoDao.getIdCentroCustoPorNome(jTextField3.getText()) != 0) {
                    jTextField3.transferFocus();
                }
            } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                if (autoCompletarCentroCusto.getjScrollPane().isVisible()) {
                    autoCompletarCentroCusto.getjList().setSelectedIndex(0);
                    autoCompletarCentroCusto.getjList().requestFocus();
                }
            } else {
                if (!autoCompletarCentroCusto.getSearchWord().equals(jTextField3.getText())) {
                    autoCompletarCentroCusto.setSearchWord(jTextField3.getText());
                    autoCompletarCentroCusto.update(new CentroCustoDao().buscar("Nome", jTextField3.getText(), true));
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }//GEN-LAST:event_jTextField3KeyReleased

    private void jList4MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList4MouseReleased
        autoCompletarInsumoNome.setSearchWord(autoCompletarInsumoNome.getjList().getSelectedValue().toString());
        autoCompletarInsumoNome.getjScrollPane().setVisible(false);
        selecionarInsumo(null, false);
    }//GEN-LAST:event_jList4MouseReleased

    private void jList4KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList4KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            autoCompletarInsumoNome.setSearchWord(autoCompletarInsumoNome.getjList().getSelectedValue().toString());
            autoCompletarInsumoNome.getjScrollPane().setVisible(false);
            selecionarInsumo(null, false);
        }
    }//GEN-LAST:event_jList4KeyReleased

    private void jRadioButton2ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButton2ItemStateChanged
        modificarOpcaoAutocompletar(jRadioButton2.isSelected());
    }//GEN-LAST:event_jRadioButton2ItemStateChanged

    private void jTextField5KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField5KeyReleased
        try {
            if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                selecionarInsumo(null, false);
            } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                if (autoCompletarInsumoNome.getjScrollPane().isVisible()) {
                    autoCompletarInsumoNome.getjList().setSelectedIndex(0);
                    autoCompletarInsumoNome.getjList().requestFocus();
                }
            } else {
                if (!autoCompletarInsumoNome.getSearchWord().equals(jTextField5.getText())) {
                    autoCompletarInsumoNome.setSearchWord(jTextField5.getText());
                    autoCompletarInsumoNome.update(new InsumoDao().buscar("Nome", jTextField5.getText(), true));
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }//GEN-LAST:event_jTextField5KeyReleased
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton6;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel44;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JList jList2;
    private javax.swing.JList jList3;
    private javax.swing.JList jList4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField10;
    private javax.swing.JTextField jTextField13;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField8;
    private javax.swing.JTextField jTextField9;
    // End of variables declaration//GEN-END:variables
}
